﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mBlog.Services;
using mBlog.ViewModels;
using mBlog.Models;
using mBlog.Extensions;

namespace mBlog.Admin.Controllers
{
    public class TagController : AdminBaseController
    {
        private ITagService tagService;
        private IPostService postService;

        public TagController(ITagService tagService, IPostService postService)
        {
            this.tagService = tagService;
            this.postService = postService;
        }
        public ActionResult List(int? page)
        {
            ListView<TagDetail> lvTags = new ListView<TagDetail>();
            var list = tagService.Get(page, ItemsPerPage);
            lvTags.List = list.MapTo<TagDetail>();

            PagerView pager = new PagerView
                                  {
                                      PageCount = (int) Math.Ceiling((double) tagService.Count()/(ItemsPerPage*2)),
                                      CurrentPage = page ?? 0,
                                      ActionName = "List",
                                      ControllerName = "Tag"
                                  };

            lvTags.Pager = pager;

            return View(lvTags);
        }

        [HttpGet]
        public ActionResult Edit(long id)
        {
            Tag tag = tagService.Single(id);

            return View(tag);
        }

        [HttpPost]
        public ActionResult Edit(long id, string name, string encodedName, bool isActive)
        {
            Tag tag = tagService.Single(id);
            if (tag != null && tag.ID > 0)
            {
                tag.Name = name;
                tag.AddedTime = DateTime.Now;
                tag.IsActive = isActive;

                tagService.Update(tag);
                return RedirectToAction("List");
            }
            else
            {
                throw new KeyNotFoundException("tag with id equals: " + id.ToString() + " doesn't exists");
            }
        }

        public ActionResult Delete(long id)
        {
            tagService.Delete(id);

            return RedirectToAction("List");
        }

        [Authorize]
        public ActionResult DeletePostTag(long postId, long tagId)
        {
            postService.DeleteTag(postId, tagId);

            return RedirectToAction("Edit", "Post", new { postId = postId });
        }

        [Authorize]
        public ActionResult AddPostTag(string addtags, long postId)
        {
            Post post = postService.Single(postId);
            string[] tags = addtags.Split(';');

            postService.AddTags(postId, tags);

            return RedirectToAction("Edit", "Post", new { postId = post.ID });
        }
    }
}
